import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { userStore } from "@/store/index";
import { router, showToast } from "@/util/index";
import { manageIndex, acceptOrder } from "@/api/index";
import { menu } from "./permission";
Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store: userStore,
    fields: ["islogin", "roles", "userInfo"],
  },
  data: {
    school: {
      name: "",
      campus: "",
    },
    permision: true,
    dataView: [],
    activeNames: [],
    blockMain: [],
    menuList: [],
    orderList: [],
  },
  goLogin() {
    router.navigateTo("/pages/login/index");
  },
  onCollapseChange(e: any) {
    this.setData({ activeNames: e.detail });
  },
  handleContact(e: any) {
    const { avatar, uid, nickname } = e.target.dataset;
    router.navigateTo("../im/index", {
      query: {
        peerId: uid,
        peerNickname: nickname,
        peerAvatar: avatar,
        isVirtualPeer: false,
        isCon: true,
      },
    });
  },
  goPage(e: any) {
    router.navigateTo(e.currentTarget.dataset.url);
  },
  async handleAccept(e) {
    let { id } = e.currentTarget.dataset;
    const res = await acceptOrder(id);
    const newData = this.data.orderList.filter((i) => i._id !== id);
    this.setData({
      orderList: newData,
    });
    showToast("接单成功!");
  },
  /**
   * 根据用户角色更新菜单列表
   */
  updateMenuListByRoles() {
    const userRoles = this.data.roles || [];

    if (userRoles.includes("master")) {
      this.setData({
        menuList: menu,
      });
      return;
    }

    const filteredMenu = menu.filter((item) => {
      if (!item.requiredRoles || item.requiredRoles.length === 0) {
        return true;
      }
      return userRoles.some((userRole) =>
        item.requiredRoles.includes(userRole)
      );
    });
    this.setData({
      menuList: filteredMenu,
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onLoad() {
    if (
      this.data.roles &&
      !this.data.roles.includes("user") &&
      this.data.roles.length !== 0
    ) {
      const data = await manageIndex();
      if (
        this.data.userInfo.uid !== data.user._id ||
        JSON.stringify(this.data.roles) !== JSON.stringify(data.user.role)
      )
        return;
      data.order.forEach((i) => {
        i.endId = i._id.slice(-8);
        i.dateTime = new Date(i.createdAt).toLocaleString();
      });
      this.setData({
        dataView: data.dv,
        orderList: data.order,
        school: {
          name: data.campus.school,
          campus: data.campus.campusName,
        },
        permision: false,
      });
      this.updateMenuListByRoles();
    }
  },
});
